package com.hxd.otc.module.order.activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.PhotoActivity;
import com.hxd.otc.main.ImagePreviewActivity;
import com.hxd.otc.module.order.adapter.ComplainAdapter;
import com.hxd.otc.module.order.adapter.ImageChooseAdapter;
import com.hxd.otc.module.order.bean.CheckImageBean;
import com.hxd.otc.module.order.bean.ComplainBean;
import com.hxd.otc.module.order.bean.ComplainTypeBean;
import com.hxd.otc.module.order.contract.ComplainContract;
import com.hxd.otc.module.order.fragment.AllOrderFragment;
import com.hxd.otc.module.order.presenter.ComplainPresenter;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.LubanUtils;
import com.hxd.otc.widget.BlocksToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * 描  述 :  ${TODO} 投诉Activity
 */
public class ComplainActivity extends PhotoActivity<ComplainPresenter> implements ComplainContract.View {
    @BindView(R.id.cause_recycler_view)
    RecyclerView mCauseRecyclerView;
    @BindView(R.id.describe_et)
    EditText mDescribeEt;
    @BindView(R.id.upload_recycler_view)
    RecyclerView mUploadRecyclerView;
    @BindView(R.id.describe_length_tv)
    TextView mDescribeLengthText;
    @BindView(R.id.submit_tv)
    TextView tvSubmit;
    @BindView(R.id.back_tv)
    TextView tvBack;
    private ComplainAdapter mCaseAdapter;
    private ComplainBean mBean;
    private ImageChooseAdapter mChooseAdapter;
    private List<CheckImageBean> mProofData;
    private static final int MAX_INPUT_CONTENT = 500;
    private static final String IMAGE_PATH_KEY = "image_path";
    private int mChoosesMaxImageLength = 3;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_complain;
    }

    @Override
    protected void initView() {
        mCauseRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        mUploadRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
    }

    @Override
    protected void initData() {
        mBean = new ComplainBean();
        mBean.orderId = getIntent().getExtras().getString(AllOrderFragment.ORDER_ID);

        if (mCaseAdapter == null) {
            mCaseAdapter = new ComplainAdapter(this);
            mCauseRecyclerView.setAdapter(mCaseAdapter);
            mCaseAdapter.setOnCaseCheckListener(new ComplainAdapter.OnCaseCheckListener() {
                @Override
                public void onCheckCase(int position, int appealTypeId) {
                    mBean.appealTypeId = appealTypeId + "";
                }
            });
        } else {
            mCaseAdapter.notifyDataSetChanged();
        }
        mProofData = new ArrayList<>();
        mPresenter.loadProof();
        mPresenter.getComplainType();
    }

    /**
     * 判断是否有填写申诉内容
     *
     * @param content
     * @return
     */
    private boolean isInputContent(@NonNull String content) {
        if (!TextUtils.isEmpty(content) && TextUtils.getTrimmedLength(content) > 0 && mBean != null) {
            mBean.content = content;
            return true;
        } else {
            BlocksToast.get().showToast(R.string.please_input_complain_content);
            return false;
        }
    }

    /**
     * 判断申述原因
     *
     * @return
     */
    private boolean isChooseCase() {
        if (mBean != null && mBean.appealTypeId != null) {
            return true;
        } else {
            BlocksToast.get().showToast(R.string.please_choose_complain_case);
            return false;
        }
    }

    /**
     * 判断是否有上传凭证
     *
     * @return
     */
    private boolean isProof() {
        if (mBean != null && mBean.complainFileData != null && mBean.complainFileData.size() > 0) {
            return true;
        } else {
//            BlocksToast.get().showToast(R.string.please_choose_complain_image);
            return false;
        }
    }

    @Override
    protected void initEvent() {
        mDescribeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mDescribeLengthText.setText(getString(R.string.appeal_et_describe_length,
                        mDescribeEt.getText().toString().length(), MAX_INPUT_CONTENT));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected ComplainPresenter createPresenter() {
        return new ComplainPresenter(this);
    }


    @OnClick({R.id.submit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submit_tv:
                clickSubmit();
                break;

        }
    }

    LubanUtils lubanUtils;

    private void clickSubmit() {
        // && isProof()
        if (isChooseCase() && isInputContent(mDescribeEt.getText().toString())) {
            size = 0;
            showSpinnerDlg(getString(R.string.please_wait), true);
            tvSubmit.setEnabled(false);
            tvSubmit.setClickable(false);

            if (isProof()) {
                if (lubanUtils == null)
                    lubanUtils = new LubanUtils();
                lubanUtils.clear();
                mBean.url = null;

                for (int i = 0; i < mBean.complainFileData.size(); i++) {
                    LogUtils.e("i==" + i + " complainFileData : " + mBean.complainFileData.get(i).getPath());
                    ArrayList<String> list = new ArrayList<>();
                    list.add(mBean.complainFileData.get(i).getPath());
                    lubanUtils.withRx(this, list, new Consumer<List<File>>() {
                        @Override
                        public void accept(final List<File> files) throws Exception {
//                        mPresenter.upLoadAliyun(files);//直接上传阿里云
                            mPresenter.uploadImage(null, files.get(0));//通过后台是上传阿里云
                        }
                    });
                }
            } else {
                mPresenter.complain(mBean);
            }
        }
    }


    @Override
    public void proofResult(List<CheckImageBean> data) {
        if (mProofData.size() > 0) {
            mProofData.clear();
        }
        mProofData.addAll(data);
        if (mCaseAdapter != null) {
            mChooseAdapter = new ImageChooseAdapter(this, mProofData);
            mUploadRecyclerView.setAdapter(mChooseAdapter);
            initProofAdapterEvent();
        } else {
            mChooseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getComplainType(List<ComplainTypeBean> beans) {

        mCaseAdapter.setmData(beans);
    }

    @Override
    public void complainSuccess(int type) {
        dismissSpinnerDlg();
        if (type == 0) {
            showToast(getResources().getString(R.string.sunmit_succed));
            setResult(RESULT_OK);
            finish();
        } else {
            dismissSpinnerDlg();
        }

    }

    @Override
    public void upLoadFinished(final int type, final Map<String, Object> success) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvSubmit.setEnabled(true);
                tvSubmit.setClickable(true);
                if (type == 0) {
                    mBean.aliyunFileData = success;
                    mPresenter.complain(mBean);
                } else {
                    showToast(getResources().getString(R.string.submit_fail));
                    dismissSpinnerDlg();
                }
            }
        });

    }

    int size;

    @Override
    public void uploadImageSuccess(String result) {

        size++;
        if (TextUtils.isEmpty(mBean.url)) {
            mBean.url = result;
        } else {
            mBean.url = mBean.url + ";" + result;
        }
        LogUtils.e(" , size : " + size + " , complainFileData :" + mBean.complainFileData.size() + "======uploadImageSuccess=" + result);
        if (size == mBean.complainFileData.size()) {//上传完成
            LogUtils.e(" , mBean : " + mBean.url);
            mPresenter.complain(mBean);
        }

    }

    @Override
    public void uploadImageFail(String message) {
        size = 0;
        LogUtils.e("======uploadImageFail========" + message);
        dismissSpinnerDlg();
        showToast(getString(R.string.submit_fail));
    }

    private void initProofAdapterEvent() {
        mChooseAdapter.setOnImageClickListener(new ImageChooseAdapter.OnImageClickListener() {
            @Override
            public void onPreview(View view, int position) {
                clickPreView(view, position);
                //预览
            }

            @Override
            public void onAdd(View view) {
                //添加状态
                showPhotoDialog();
            }

            @Override
            public void onDelete(View view) {
                mChoosesMaxImageLength++;
                clickDelete();
            }


        });
    }


    /**
     * 删除图片
     */
    private void clickDelete() {
        if (mProofData.size() > 0) {
            mBean.complainFileData.clear();
            for (int i = 0; i < mProofData.size(); i++) {
                if (mProofData.get(i).isImage) {
                    mBean.complainFileData.add(new File(mProofData.get(i).imagePath));
                }
            }
        }
    }

    private void clickPreView(View view, int position) {
        if (mProofData.size() > 0) {
            ArrayList<String> previewData = new ArrayList<>();
            for (int i = 0; i < mProofData.size(); i++) {
                if (mProofData.get(i).isImage) {
                    previewData.add(mProofData.get(i).imagePath);
                }
            }

            Intent intent = new Intent(this, ImagePreviewActivity.class);

            LogUtils.w("clickPreView--", previewData.toArray().length + "");
            intent.putStringArrayListExtra(Constant.Order.PREVIEW_IMAGE_PATH_KEY, previewData);
            intent.putExtra(Constant.Order.PREVIEW_IMAGE_POSITION, position);
            startActivity(intent);
        }

    }

    private String[] listFile2Path() {
        return null;
    }

    @Override
    protected void openDialogCamera() {
        openCamera();
    }

    @Override
    protected void openDialogAlbum() {
        openAlbum(mChoosesMaxImageLength);

    }

    @Override
    protected void imageFileResult(@NonNull List<File> imageFiles) {
        if (imageFiles.size() > 0) {
            mChoosesMaxImageLength -= imageFiles.size();
            for (int i = 0; i < imageFiles.size(); i++) {
                CheckImageBean imageBean = new CheckImageBean();
                imageBean.isImage = true;
                imageBean.imagePath = imageFiles.get(i).getAbsolutePath();
                mProofData.add(mProofData.size() - 1, imageBean);
            }
            mBean.complainFileData.addAll(imageFiles);
            mChooseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (lubanUtils != null) {
            lubanUtils.clear();
            lubanUtils = null;
        }
    }

    @Override
    public void onError(int code) {
        super.onError(code);
        tvSubmit.setEnabled(false);
        tvSubmit.setClickable(false);
    }
}
